package ywpt.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;

import ywpt.components.acegi.domain.Function;
import ywpt.components.acegi.domain.Operation;
import ywpt.components.acegi.domain.Role;
import ywpt.core.dao.extend.HibernateEntityExtendDao;

public class OperationServiceImpl extends HibernateEntityExtendDao<Operation> implements OperationService {

	@Override
	public List<Operation> getAllOperations() {
		return this.getAll();
	}

	@Override
	public Operation getOperationById(Long id) {
		return this.get(id);
	}

	@Override
	public Operation getOperationByOperationName(String operationName) {
		return this.findUniqueBy("operationName", operationName);
	}


	@Override
	public List getOperationTree(Long parentId, List roles) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getOperationTree(Long parentId) {
		String hql = "from ywpt.components.acegi.domain.Operation as f";
		if (parentId != null) {
			hql = hql + " where f.parent.id=" + parentId;
		} else {
			hql = hql + " where f.parent.id is null";
		}
		List<Operation> childList = super.find(hql);
		List jsonList = new ArrayList();
		for (int i = 0; i < childList.size(); i++) {
			Operation row = childList.get(i);
			Map child = new HashMap();
			child.put("text", row.getOperationName());
			child.put("id", row.getId());
			List grandChildRow = getOperationTree(row.getId());
			if (grandChildRow.size() != 0) {
				child.put("children", grandChildRow);
			} else {
				child.put("leaf", Boolean.TRUE);
				child.put("iconCls", "tree-node-leaf");
				child.put("code", row.getOperationCode());
			}
			jsonList.add(child);
		}
		return jsonList;
	}

	@Override
	public List<Operation> getOperations(DetachedCriteria query) {
		return this.findAllByCriteria(query);
	}

	@Override
	public List<Operation> getOperations(DetachedCriteria query, int pageSize,
			int startIndex) {
		return this.findAllByCriteria(query, pageSize, startIndex);
	}

	@Override
	public int getOperationsCount(DetachedCriteria query) {
		return this.getCountByCriteria(query);
	}

	@Override
	public void addRoles(Operation oper, List<Long> roles) {
		if(roles!=null && roles.size()>0)
			oper.setRoles(new HashSet<Role>(0));
		for(int i=0,j=roles.size();i<j;i++)
		{
			Role role=(Role) this.get(Role.class,roles.get(i));
			oper.getRoles().add(role);
		}
		super.update(oper);
		
	}
	
	@Override
	public int[] removeRoles(Operation oper, Long[] ids) {
		for(int i=0;i<ids.length;i++)
		{
			Role role=super.get(Role.class, ids[i]);
			oper.getRoles().remove(role);
		}
		super.update(oper);
		int results[] = new int[ids.length];
		for (int i = 0; i < ids.length; i++) {
			results[i] = 1;
		}
		return results;
	}


}
